<?php

namespace app\admin\controller\product_lists;

use app\common\controller\Backend;
use Think\Db;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Products extends Backend
{
    
    /**
     * Products模型对象
     * @var \app\admin\model\product_lists\Products
     */
    protected $model = null;
    protected $searchFields = 'id,name,bn';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\product_lists\Products;
        $this->view->assign("accessList", $this->model->getAccessList());
        $this->view->assign("statusList", $this->model->getStatusList());
        if(isset($_GET['status'])){
            if($_GET['status'] == 'radio'){
                $this->view->assign("status", 'radio');
            }elseif($_GET['status'] == 'check'){
                $this->view->assign("status", 'check');
            }else{
                $this->view->assign("status", '');
            }
        }else{
            $this->view->assign("status", '');
        }
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    public function checkdata(){
        if($this->request->post('temp/a')){
            $data = $this->request->post('temp/a');
            $this->success('success',null,$data);
        }else{
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if(isset($_GET['status'])){
                if($_GET['status'] == 'radio' && !isset($_GET['action'])){
                    $where1['access'] = array('in',array('outsourcing','self','virtual'));
                    $total = $this->model
                        ->with(['categorys'])
                        ->where($where)
                        ->where($where1)
                        ->order($sort, $order)
                        ->count();

                    $list = $this->model
                        ->with(['categorys'])
                        ->where($where)
                        ->where($where1)
                        ->order($sort, $order)
                        ->limit($offset, $limit)
                        ->select();
                }else{
                    $total = $this->model
                        ->with(['categorys'])
                        ->where($where)
                        ->order($sort, $order)
                        ->count();

                    $list = $this->model
                        ->with(['categorys'])
                        ->where($where)
                        ->order($sort, $order)
                        ->limit($offset, $limit)
                        ->select();
                }
            }else{
                $total = $this->model
                    ->with(['categorys'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['categorys'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }
            foreach ($list as $row) {


            }
            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $this->model = Db::name('products');
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $count = $this->model->where($pk, 'in', $ids)->update(array('deletetime' => time()));
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }
    //获取id
    public function get_id(){}
    /*
     * 查看工单
     * */
    public function bomlist(){

        $post = $this->request->request('temp/a');
        $arr = array();
        if(isset($post[0]['num']) && $post[0]['num']){
            $num = $post[0]['num'];
        }else{
            $num = 1;
        }
        if(isset($post[0]['name']) && $post[0]['name']){
            $name = $post[0]['name'];
        }else{
            $name = '';
        }
        if(isset($post[0]['bn']) && $post[0]['bn']){
            $bn = $post[0]['bn'];
        }else{
            $bn = '';
        }
        $this->get_bom($post[0]['bn'],$arr);
        $part_pro = $pro = array();
        if(!empty($arr)){
            foreach($arr as $key => $val){
                $val['Dosage'] = $num*$val['Dosage'];
                if(!$val['num']){
                    $val['num'] = 0;
                }
                if(in_array($val['access'],array('outsourcing','self','virtual'))){
                    $part_pro[$val['c_bn']][] = $val;
                }else{
                    $pro[$val['c_bn']][] = $val;
                }
            }
            if(!empty($part_pro)){
                foreach($part_pro as $key => $val){
                    $Dosage = 0;
                    foreach($val as $k => $v){
                        $Dosage += $v['Dosage'];
                        $part_pro[$key] = $v;
                    }
                    $part_pro[$key]['Dosage'] = $Dosage;
                }
            }
            if(!empty($pro)){
                foreach($pro as $key => $val){
                    $Dosage = 0;
                    foreach($val as $k => $v){
                        $Dosage += $v['Dosage'];
                        $pro[$key] = $v;
                    }
                    $pro[$key]['Dosage'] = $Dosage;
                }
            }
        }
        $this->assign('num',$num);
        $this->assign('product_name',$name);
        $this->assign('bn',$bn);
        $this->assign('part_pro',array_values($part_pro));
        $this->assign('pro',array_values($pro));
        return $this->view->fetch();
    }
    //根据产品编号获取原材料和半成品结果
    public function get_bom($product_bn='',&$arr=array(),$bns = array()){
        $bns[] = $product_bn;
        $model = new \app\admin\model\bomlists\Bomlist;
        if($product_bn){
            $sql = "SELECT * FROM fa_bomlist as b LEFT JOIN fa_products as p ON b.c_bn=p.bn
                    LEFT JOIN fa_stock as s ON b.c_bn=s.product_bn
                    WHERE b.p_bn='".$product_bn."'";
            $model_res = Db::query($sql);
            //循环所有数据找$product_bn的儿子
            if(!empty($model_res)){
                foreach ($model_res as $key => $datum) {
                    //保存下来，然后继续找儿子的儿子
                    if(!in_array($datum,$arr)){
                        $arr[] = $datum;
                    }
                    if (!in_array($datum['c_bn'],$bns)) {
                        $this->get_bom($datum['c_bn'], $arr,$bns);
                    }
                }
            }
        }
    }
}
